<template>
  <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
    <template #title>
      上传文件
    </template>
    <a-form ref="formRef" :model="form" auto-label-width class="w-full">
      <a-form-item label="上传文件" field="name">
        <a-upload multiple draggable :action="uploadUrl" :headers="header" @success="handleSuccess"
          @error="handleError" />
      </a-form-item>
      <!-- 为每个上传的文件显示文件名输入框 -->
      <a-form-item v-for="(item, index) in fileList" :key="index" :label="'文件名称' + (index + 1)"
        :field="'fileName' + index" :rules="[{ required: true, message: '请输入文件名称' }]">
        <a-input v-model="item.name" placeholder="文件名称" allow-clear />
      </a-form-item>
      <a-form-item label="标签" field="tagNames" :rules="[{ required: true, message: '请选择标签名称' }]">
        <a-select v-model="form.tagNames" placeholder="请选择标签" allow-create multiple>
          <a-option v-for="item in tagList" :key="item.tagId" :label="item.title" :value="item.title" />
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, computed } from 'vue'
import { fileSave, fileTagList } from '@/apis/file'
import { Message } from '@arco-design/web-vue'
import { getToken } from '@/utils/auth'

const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/file/oss/upload'
const header = computed(() => {
  return {
    "Authorization": getToken() || ''
  }
})

const visible = ref(false)

const tagNames = ref([])
const fileList = ref([])

const form = ref({
  name: '',
  parentId: 0,
  tagNames: [],
  src: '',
  size: 0
})

const tagList = ref([])

const handleSuccess = (file) => {
  const res = file.response
  if (res.code == 200) {
    // 添加上传成功的文件到列表中
    fileList.value.push({
      ...res.data,
      name: res.data.name,
      parentId: form.value.parentId
    })
    console.log("文件", fileList.value)
    Message.success('上传成功')
  } else {
    Message.error('上传失败,请重试')
  }
}

const handleError = () => {
  Message.error('上传失败,请重试')
}

const open = (parentId) => {
  loadTagList()
  // 重置文件列表
  fileList.value = []
  form.value = {
    name: '',
    src: '',
    parentId: 0,
    tagNames: [],
    size: 0
  }
  if (parentId) {
    form.value.parentId = parentId
  }
  visible.value = true
}

const loadTagList = async () => {
  const res = await fileTagList()
  tagList.value = res.data
}

const emit = defineEmits(['success'])

const handleOk = async () => {
  // 保存所有文件
  let data = {
    tagNames: form.value.tagNames,
    list: fileList.value
  }
  console.log("表单对象", data)
   await fileSave(data)
  Message.success('创建成功')
  emit('success')
  visible.value = false
}

const handleCancel = () => {
  visible.value = false
}

defineExpose({
  open
})
</script>